import Notebook from '@/apis/notebooks.js'
import { Message } from 'element-ui'
const store = {
  // data
  state: {
    notebooks: null,
    curBookId: null,
  },
  //计算属性 computed
  getters: {
    notebooks: (state) => state.notebooks || [],
    curBook: (state) => {
      if (!Array.isArray(state.notebooks)) return {}
      if (!state.curBookId) return state.notebooks[0] || {}
      return (
        state.notebooks.find((notebook) => notebook.id == state.curBookId) || {}
      )
    },
  },

  // 方法 methods 不能操作异步函数
  mutations: {
    setNotebooks(state, payload) {
      state.notebooks = payload.notebooks
    },

    addNotebook(state, payload) {
      state.notebooks.unshift(payload.notebook)
    },

    updateNotebook(state, payload) {
      let notebook =
        state.notebooks.find((notebook) => notebook.id == payload.notebookId) ||
        {}
      notebook.title = payload.title
    },

    deleteNotebook(state, payload) {
      state.notebooks = state.notebooks.filter(
        (notebook) => notebook.id != payload.notebookId
      )
    },
    setCurBook(state, payload) {
      state.curBookId = payload.curBookId
    },
  },

  //Action 类似于 mutation，不同在于：Action 提交的是 mutation，而不是直接变更状态 Action 可以包含任意异步操作
  actions: {
    getNotebooks({ commit, state }) {
      if (state.notebooks !== null) return Promise.resolve() // 如果notebooks有值就直接將值返回，沒值的時候再請求數據
      return Notebook.getAll().then((res) => {
        commit('setNotebooks', {
          notebooks: res.data,
        })
      })
    },

    // 更新笔记本title
    updateNotebook({ commit }, payload) {
      return Notebook.updateNotebook(payload.notebookId, {
        title: payload.title,
      }).then((res) => {
        commit('updateNotebook', {
          notebookId: payload.notebookId,
          title: payload.title,
        })
        Message({
          type: 'success',
          message: res.msg,
        })
      })
    },

    // 删除笔记本
    deleteNotebook({ commit }, payload) {
      return Notebook.deleteNotebook(payload.notebookId).then((res) => {
        commit('deleteNotebook', {
          notebookId: payload.notebookId,
        })
        Message({
          type: 'success',
          message: res.msg,
        })
      })
    },

    // 创建笔记本
    addNotebook({ commit }, payload) {
      return Notebook.addNotebook({
        title: payload.title,
      }).then((res) => {
        commit('addNotebook', {
          notebook: res.data,
        })
        Message({
          type: 'success',
          message: res.msg,
        })
      })
    },
  },
}

export default store
